//
//  HomeTableViewCell.swift
//  CBWWeiBo
//
//  Created by 陈博文 on 16/1/13.
//  Copyright © 2016年 陈博文. All rights reserved.
//

import UIKit
import SDWebImage

class HomeTableViewCell: UITableViewCell {

    // MARK:- 属性连线
    @IBOutlet weak var verifiedImageView: UIImageView!
    @IBOutlet weak var contentTextLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var sourceLabel: UILabel!
    @IBOutlet weak var vipImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var iconImageView: UIImageView!
    @IBOutlet weak var pictureCollectionView: UICollectionView!
    @IBOutlet weak var pictureColHeightCons: NSLayoutConstraint!
    @IBOutlet weak var pictureColWidthCons: NSLayoutConstraint!
    @IBOutlet weak var pictureColLayout: UICollectionViewFlowLayout!

    @IBOutlet weak var bottomView: UIView!
    
    var viewModel: StatusViewModel?
        {
        didSet
        {
            //CBWLog("给cell设置viewModel")
            /*
            M: 负责准备数据
            V: 负责显示数据
            C: 桥梁
            */
            // 1.设置头像
            
            iconImageView.sd_setImageWithURL(viewModel?.icon_image_url)
            
            // 2.设置认证图标
            verifiedImageView.image = viewModel?.verified_image
            
            // 3.设置昵称
            nameLabel.text = viewModel?.status.user?.screen_name
            
            // 4.设置会员图标
            vipImageView.image = viewModel?.mbImage
            
            // 5.设置时间
            timeLabel.text = viewModel?.created_str
            
            // 6.设置来源
            sourceLabel.text = viewModel?.source_str
            
            // 7.设置在正文
            contentTextLabel?.text = viewModel?.status.text
            // 8.计算尺寸
//            CBWLog(calculate())
            let (itemSize, colSize) = calculate()
            pictureColHeightCons.constant = colSize.height
            pictureColWidthCons.constant = colSize.width
            // 8.2设置cell尺寸
            if itemSize != CGSizeZero {
                pictureColLayout.itemSize = itemSize
            }
            // 8.3刷新表格
            pictureCollectionView.reloadData()
            pictureCollectionView.layoutIfNeeded()

        }
    }
    // MARK:=============== 计算图片的尺寸 ===============
    /// 计算配图尺寸(cell尺寸, collectionView尺寸)
    // 元组应用场景, 一般用户函数返回值, 和一些临时性的数据保存, 如果想保存永久性的数据, 请使用类和结构体
//let (itemSize, colSize) = calculate()
    private func calculate() -> (CGSize, CGSize)
    {
        // 1.获取配图个数
        let count = viewModel?.status.pic_urls?.count ?? 0
        
        // 2.判断配图个数
        // 2.1没有配图
        if count == 0
        {
            return (CGSizeZero, CGSizeZero)
        }
        // 2.2单张配图
        if count == 1
        {
            // 1.拿到图片
            let dict = viewModel!.status.pic_urls!.first!
            let key = dict["thumbnail_pic"] as! String
            // 注意: key就是当初下载图片的url字符串
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            // 2.返回尺寸
            return (image.size, image.size)
        }
        //        let imageWidth = 90
        //        let imageHeight = 90
        let imageMargin: CGFloat = 10
        var col = 3
        let imageWidth = (UIScreen.mainScreen().bounds.width - CGFloat(col + 1) * imageMargin) / CGFloat(col)
        let imageHeight = imageWidth
        
        var row = 0
        if count == 4
        {
            // 2.3四张配图
            col = 2
            row = col
        }else
        {
            // 2.4其他张配图
            col = 3
            row = (count - 1) / 3 + 1
        }
        
        // 图片宽度 * 列数 + (列数 - 1) * 间隙
        let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
        let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
        
        return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
        
    }

    
    // MARK:=============== 初始化操作 ===============
    override func awakeFromNib() {
        super.awakeFromNib()
        // 设置正在最大的宽度, 推荐
        contentTextLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - (2 * 10)
        //设置头像为圆
        iconImageView.layer.cornerRadius = 25
    }
    
    // MARK:=============== 返回标示符 ===============
    class func identifier() -> String {
        return "homeCell"
    }

// MARK:=============== 计算行高 ===============
/// 根据传入的数据计算当前数据对应的行高
func calculateRowHeight(viewModel: StatusViewModel) -> CGFloat
{
    // 1.设置数据
    self.viewModel = viewModel
    // 2.更新界面
    self.layoutIfNeeded()
    // 3.获取底部工具条最大的Y值
    return CGRectGetMaxY(bottomView.frame)
}
}
// MARK:=============== collectionView 数据源 ===============
extension HomeTableViewCell: UICollectionViewDataSource
{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.status.pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HomePictureCell.identifier(), forIndexPath: indexPath) as! HomePictureCell
        
        let dict = viewModel!.status.pic_urls![indexPath.item]
        let url = NSURL(string: (dict["thumbnail_pic"] as? String) ?? "")
//        CBWLog(url)
        cell.imageView.sd_setImageWithURL(url)
        
        return cell
    }
}





class HomePictureCell: UICollectionViewCell {
    
    @IBOutlet weak var imageView: UIImageView!
    
    class func identifier() ->String {
        return "pictureCell"
    }
}
